package com.xmb.quick.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.xmb.quick.annotation.Log;
import com.xmb.quick.constant.LayTableR;
import com.xmb.quick.constant.R;
import com.xmb.quick.entity.SysMenu;
import com.xmb.quick.entity.SysRole;
import com.xmb.quick.entity.SysRolePermission;
import com.xmb.quick.entity.SysUser;
import com.xmb.quick.service.ISysMenuService;
import com.xmb.quick.service.ISysRolePermissionService;
import com.xmb.quick.service.ISysRoleService;
import com.xmb.quick.service.ISysUserService;

@Controller
@RequestMapping("/permission")
public class PermissionController {
	
	@Autowired
	private ISysRoleService iSysRoleService;

	@Autowired
	private ISysMenuService iSysMenuService;
	
	@Autowired
	private ISysRolePermissionService iSysRolePermissionService;
	
	@Autowired
	private ISysUserService iSysUserService;
	
	@GetMapping("/index")
	public String index() {
		return "permission/index";
	}
	
	@GetMapping("/addHtml")
	public String addHtml() {
		return "permission/add";
	}
	
	@GetMapping("/editHtml")
	public String editHtml(String id,Model model) {
		model.addAttribute("role", iSysRoleService.selectInfoOne(new EntityWrapper<SysRole>().eq("id", id)));
		return "permission/edit";
	}

	@PostMapping("/roleList")
	@ResponseBody
	public LayTableR roleList(Integer page,Integer limit,String searchCode) {
		EntityWrapper<SysRole> ew = new EntityWrapper<SysRole>();
		if(StringUtils.isNotEmpty(searchCode)) {
			ew.where("role_code={0}",searchCode).or().where("role_name={0}",searchCode);
		}
		Page<SysRole> rolePage = iSysRoleService.selectInfoPage(new Page<SysRole>(page, limit),ew);
		return LayTableR.result(0, rolePage.getTotal(), rolePage.getRecords());
	}
	
	@Log("添加角色")
	@PostMapping("/addRole")
	@ResponseBody
	public R addRole(SysRole sysRole) {
		SysRole role = iSysRoleService.selectInfoOne(new EntityWrapper<SysRole>().eq("role_code", sysRole.getRoleCode()));
		if(role != null) {
			return R.error("角色代码已存在");
		}
		try {
			iSysRoleService.add(sysRole);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统异常");
		}
		return R.ok();
	}
	
	@Log("修改角色")
	@PostMapping("/editRole")
	@ResponseBody
	public R editRole(SysRole sysRole) {
		try {
			iSysRoleService.edit(sysRole);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统异常");
		}
		return R.ok();
	}
	
	@Log("删除角色")
	@PostMapping("/deleteRole")
	@ResponseBody
	public R deleteRole(String id) {
		try {
			List<SysUser> userList = iSysUserService.selectInfoList(new EntityWrapper<SysUser>().eq("role_id", id));
			if(userList.size()>0) {
				return R.error("已有用户赋予了该角色，无法删除！");
			}
			iSysRoleService.remove(new EntityWrapper<SysRole>().eq("id", id));
			//删除已赋予的权限
			iSysRolePermissionService.remove(new EntityWrapper<SysRolePermission>().eq("role_id", id));
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统异常");
		}
		return R.ok();
	}
	
	@Log("权限赋权")
	@PostMapping("/comfire_permission")
	@ResponseBody
	public R comfire_permission(String roleId,String permissionIds) {
		try {
			if(StringUtils.isEmpty(roleId)) {
				return R.error("有必填项为空");
			}
			List<String> pids = JSON.parseArray(permissionIds, String.class);
			//删除当前角色之前权限
			iSysRolePermissionService.remove(new EntityWrapper<SysRolePermission>().eq("role_id", roleId));
			//添加新赋予的权限
			List<SysRolePermission> list = new ArrayList<SysRolePermission>();
			for (String id : pids) {
				SysRolePermission sysRolePermission = new SysRolePermission();
				sysRolePermission.setRoleId(roleId);
				sysRolePermission.setPermissionId(id);
				list.add(sysRolePermission);
			}
			if(list.size()>0) {
				iSysRolePermissionService.add(list);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统异常");
		}
		return R.ok();
	}
	
	@PostMapping("/menuList")
	@ResponseBody
	public Object menuList(String roleId) {
		//返回map
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//根据roleId查询权限Id集合      中间表
		List<SysRolePermission> rolePermissions = iSysRolePermissionService.selectInfoList(new EntityWrapper<SysRolePermission>().where("role_id = {0}", roleId));
		//角色本身所拥有的的权限
		List<SysMenu> menulist = null;
		if(rolePermissions.size() != 0) {
			List<String> permissionIds = new ArrayList<String>();
			for (SysRolePermission sysRolePermission : rolePermissions) {
				permissionIds.add(sysRolePermission.getPermissionId());
			}
			//根据权限Ids查询相应信息
			menulist = iSysMenuService.selectInfoList(new EntityWrapper<SysMenu>().in("id", permissionIds));
		}
		//返回状态码
		resultMap.put("code", 0);
		resultMap.put("data", getChildren(null, menulist));
		return resultMap;
	}
	
	public List<Map<String, Object>> getChildren(String pid, List<SysMenu> menuList) {
		List<Map<String, Object>> data = new ArrayList<Map<String,Object>>();
		Map<String,Object> map = null;
		List<SysMenu> childredPermissions = null;
		if(StringUtils.isEmpty(pid)) {
			childredPermissions = iSysMenuService.selectInfoList(new EntityWrapper<SysMenu>().where("supper_id=''").or().isNull("supper_id").or().where("supper_id='0'"));
		}else {
			childredPermissions = iSysMenuService.selectInfoList(new EntityWrapper<SysMenu>().where("supper_id = {0}", pid));
		}
		for (SysMenu sysMenu : childredPermissions) {
			map = new HashMap<String, Object>();
			map.put("id", sysMenu.getId());
			map.put("label", sysMenu.getMenuName());
			int count = iSysMenuService.selectInfoCount(new EntityWrapper<SysMenu>().where("supper_id = {0}", sysMenu.getId()));
			if(menuList != null) {
				for (SysMenu menu : menuList) {
					if(sysMenu.getId().equals(menu.getId()) && count == 0) {
						map.put("checked", true);
						break;
					}
				}
			}
			if(count != 0) {
				map.put("children", getChildren(sysMenu.getId(), menuList));
			}
			data.add(map);
		}
		return data;
	}
	
	public List<Map<String, Object>> GetChildren(List<Map<String, Object>> treeList,SysMenu menu, List<SysMenu> menuList) {
		for (SysMenu sysMenu : menuList) {
			if (menu.getId().equals(sysMenu.getSupperId())) {
				Map<String,Object> tree = new HashMap<String, Object>();
				tree.put("id", sysMenu.getId());
				tree.put("name", sysMenu.getMenuName());
				tree.put("pId", sysMenu.getSupperId());
				treeList.add(tree);
				// 递归调用
				treeList = GetChildren(treeList,sysMenu, menuList);
			}
		}
		return treeList;
	}
}
